import AMapLoader from '@amap/amap-jsapi-loader';

export default class AMaps {
  constructor(options) {
    this.options = options;
  }

  initMap() {
    return new Promise((resolve, reject) => {
      AMapLoader.load({
        key: this.options.key || '788bc2886be41fdafa1879d9906e8e5d', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: this.options.version || '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.PlaceSearch', 'AMap.Geocoder'].concat(this.options.plugins), // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.instance = AMap;
          this.geocoder = new AMap.Geocoder({extensions: 'all'});
          this.map = new AMap.Map(
            this.options.dom,
            this.options.setting || {
              //设置地图容器id
              viewMode: '3D', //是否为3D地图模式
              zoom: 12, //初始化地图级别
              animateEnable: false,
            }
          );
          this.placeSearch = new AMap.PlaceSearch({
            extensions: 'all',
            pageSize: 15,
            map: this.map, // 展现结果的地图实例
            panel: "panel", // 结果列表将在此容器中进行展示。
            autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
          });
          this.placeSearch.on("selectChanged",(e)=> {
            const data = e.selected.data;
            const temp = {
              province: data.pname,
              provinceCode: data.pcode,
              city: data.cityname,
              cityCode: data.citycode,
              county: data.adname,
              countyCode: data.adcode,
              storeAddr: data.address,
              address: data.pname + data.cityname + data.adname + data.address,
              lng: `${data.location.lng}`,
              lat: `${data.location.lat}`
            }
            this.selectAddress = {...temp}
          })
          const ToolBar = new AMap.ToolBar();
          const Scale = new AMap.Scale();

          this.map.addControl(ToolBar);
          this.map.addControl(Scale);

          const marker = new this.instance.Marker({
            icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
            position: [22, 22],
            offset: new this.instance.Pixel(-10, -35),
            visible: false,
          });
          this.marker = marker;
          this.map.add(marker);

          this.map.on('click', (e) => {
            this.setPosition(e.lnglat);
          });
          resolve(true);
        })
        .catch((e) => {
          reject(e);
        });
    });
  }

  //地图点击定位标记及展示
  setPosition(position) {
    this.geocoder.getAddress(position, async (status, result) => {
      //console.log(status, result);
      if (status === 'complete' && result.info === 'OK') {
        const {addressComponent, formattedAddress} = result.regeocode;
        const {province, city, district} = addressComponent;
        this.address = {province, city, district, detail: formattedAddress};
        this.marker.setPosition(position);
        this.marker.show();

        const infoWindow = new this.instance.InfoWindow({
          anchor: 'bottom-center',
          content: `<div style="padding: 10px;">${result.regeocode.formattedAddress}</div>`,
          offset: new this.instance.Pixel(0, -38),
        });
        infoWindow.open(this.map, position);
        this.selectAddress = {
          address: formattedAddress,
          lng: String(position.lng),
          lat: String(position.lat)
        }
        //this.address = await this.translateAddress(this.address);
        //console.log(this.address);
      }
    });
  }

  //重新设置地图中心点
  changeMapCenter(position) {
    this.map.setZoomAndCenter(16, position);
  }

  //地址搜索功能，返回所有结果集
  search(str) {
    return new Promise((resolve, reject) => {
      this.placeSearch.search(str, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          resolve(result);
        }
      });
    });
  }

  //选择地址移动到地址处并展示，为了配合搜索选择后重新定位
  // position:坐标; option:完整位置对象信息
  selectFun(position, option) {
    this.changeMapCenter(position);

    const {pname, cityname, adname, address, name} = option;
    this.address = {province: pname, city: cityname, district: adname, detail: address + name};
    this.marker.setPosition(position);
    this.marker.show();

    const infoWindow = new this.instance.InfoWindow({
      anchor: 'bottom-center',
      content: `<div style="padding: 10px;">${
        pname + (cityname === pname ? '' : cityname) + adname + address + name
      }</div>`,
      offset: new this.instance.Pixel(0, -38),
    });
    infoWindow.open(this.map, position);
    //this.address = await this.translateAddress(this.address);
  }

  //获取地址信息
  getAddress() {
    return this.selectAddress;
  }

  //设置地址信息，取搜索结果集的第一个值进行设置
  setAddress(str) {
    this.search(str).then((res) => {
      if (res.info === 'OK') {
        let firstObj = res.poiList.pois[0];
        let position = [firstObj.location.lng, firstObj.location.lat];
        this.selectFun(position, firstObj);
      }
    });
  }
}
